window.$loading = $('.com-loading');
var DATA_STATUS = {
    DELETED: '0',
    ONLINE: '1',
    OFFLINE: '2',
};
function toFixed(num, s) {
    var times = Math.pow(10, s)
    var des = num * times + 0.5
    des = parseInt(des, 10) / times
    return des + ''
}
var CURRENT_ROUTER = 'HP_CURRENT_ROUTER';
var LOGOUT_URL = '/admin/login.html', MANAGER_CURRENT = '', LOADING_USER = false,
    FETCH_STATUS = {
        USERS: false,

    },
    FETCH_DATA = {
        USERS: ''
    }, MODULE_ = 'MODULE', _MODULE = ['CRM', 'S', 'C', 'CK', 'CW', 'PI', 'SYS'];
/**
 * @date 2017-05-07
 * @desc
 */
function loadingFadeOut() {
    $('.com-loading').length && $('.com-loading').fadeOut(); // code updated at 2017-05-23 08:56
}
var hkey_root, hkey_path, hkey_key,
    hkey_root = "HKEY_CURRENT_USER",
    hkey_path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
//设置网页打印的页眉页脚为空
function pagesetup_null() {
    try {
        var RegWsh = new ActiveXObject("WScript.Shell");
        hkey_key = "header";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "");
        hkey_key = "footer";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "")
    } catch (e) {
    }
}
/***
 * 获取应付余额
 */
function getYingFuRemain(obj, prefix) {
    var prefix = prefix || 'order';
    var currentTotalRemain = floatTool.subtract(obj[prefix + 'Payable'], obj[prefix + 'NetPay']);
    currentTotalRemain = floatTool.subtract(currentTotalRemain, obj[prefix + 'Receivable']);
    currentTotalRemain = floatTool.add(currentTotalRemain, obj[prefix + 'Receipts']);
    return currentTotalRemain;
}
/***
 *  实付金额
 * @param obj
 * @param prefix
 * @returns {*}
 */
function getActualPayTotal(obj, prefix) {
    var prefix = prefix || 'order';
    return floatTool.subtract(obj[prefix + 'NetPay'], obj[prefix + 'Receivable']);
}
/***
 * 应付金额
 * @param obj
 * @param prefix
 * @returns {*}
 */
function getYingFuTotal(obj, prefix) {
    var prefix = prefix || 'order';
    return floatTool.subtract(obj[prefix + 'Payable'], obj[prefix + 'Receipts']);
}
function pagesetup_default() {
    try {
        var RegWsh = new ActiveXObject("WScript.Shell");
        hkey_key = "header";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "&w&b页码，&p/&P");
        hkey_key = "footer";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "&u&b&d")

        //以下设置页面边距
        hkey_key = "margin_bottom";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0");
        hkey_key = "margin_left";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0.1");
        hkey_key = "margin_right";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0.1");
        hkey_key = "margin_top";
        RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0.4");
    } catch (e) {
    }
}
/**
 * @date 2017-05-11
 * @desc
 * @param page 分页对象 {size:'',total:''}
 * @param query 查询参数 {}
 * @param search 搜索函数
 */
function pageInit(page, query, search) {
    if (!page) {
        return;
    }
    var page_ = $('.su-pager').data('pagination');
    // if (!page_ || (query.size && query.size != page_.pageSize) || (page_.itemsCount != page.total) || (page.page == 1) || (page.page == '') || (page.page == undefined)) {

    $('.su-pager').data('pagination', 'init');
    $('.su-pager').extendPagination({
        totalCount: page.total || 0, // 总数
        page: page.page,
        showPage: 10, //分页栏展示数(默认10)
        limit: page.size == 0 ? 15 : page.size, // 每页数量
        callback: function (curr, limit, totalCount) {
            if (query.query) {
                search($.extend({}, query, {query: $.extend({}, query.query, {page: curr})}))
            } else {
                search({page: curr});
            }
            return false;
        }
    });


    if (!$('.size-select').length) {
        $('.su-pager').prepend(generatePageSize(page.size == 0 ? 15 : page.size, page.total));
        $('.size-select').unbind('change').change(function (item) {
            var size = $(item.target).val();
            if (query.query) {
                search($.extend({}, query, {query: $.extend({}, query.query, {size: size, page: 1})}))
            } else {
                search({size: size, page: 1});
            }
        })
    }
    if (!$('.su-pager').find('.clearfix').length) {
        $('.su-pager').append('<div class="clearfix"></div>');
    }
    // }
}

function initSummaryToDetail() {
    onClick($('.order-detail'), function () {
        var item = $(this).data('json');
        window.location = './order.html?clienteleName=' + item.clienteleName + '&unitCode=' + item.unitCode + '&monthStart=' + $('[name=monthStart]').val() + '&monthEnd=' + $('[name=monthEnd]').val()
    });
    onClick($('.bill-detail'), function () {
        var item = $(this).data('json');
        window.location = './bill.html?clienteleName=' + item.clienteleName + '&unitCode=' + item.unitCode + '&monthStart=' + $('[name=monthStart]').val() + '&monthEnd=' + $('[name=monthEnd]').val()
    });
}


// const LOGOUT_URL = '/admin/';
/**
 * b布局初始化函数
 */
function initIframe() {

    if ($('iframe').length) {
        $('iframe').height($(window).height() - 50);
        $('iframe')[0].onloadstart = (function () {
            console.log('loadstart');
        });
        $('.main-sidebar').height($(window).height());
        $('iframe').load(function () {
            NProgress && NProgress.done();
            loadingFadeOut();
        })
    } else {
        setTimeout(function () {
            loadingFadeOut();
        }, 1000);
        if ((!!$('.treeview.active').length) || !!$('.module-nav .active').length) {
            return;
        }
        parent.getMenusList()
            .then(function (menus) {
                $('.module-nav').html('');
                console.log(menus);
                _.sortBy(menus, 'orderNum').map(function (item) {
                    if (item.level != 1)return; //非1级菜单
                    $('.module-nav').append('<li  id="menu' + item.id + '" > \
                    <a href="javascript:void(0);" onclick="parent.window.setCurrentModule(' + item.id + ');"> \
                    <i class="icon-drawer" aria-hidden="true"></i> \
                    ' + item.name + ' \
                    </a> \
                    </li>');
                });
                initModuleLabel();
            })

    }
    if ($('iframe[name=main]').length) {
        $('iframe[name=main]').height($(window).height())
    } else {
        if (window.parent && $(window.parent.document).find('iframe[name=sub-main]').length) {
            // do nothing
        } else {
            if (window.location.href.indexOf('express/prin') == -1) {
                $('body').css({'overflowY': 'auto', paddingTop: '50px'});
            }

        }
        var $sub = $('iframe[name=sub-main]');
        if ($sub && $sub.length) {
            $sub.height($(window).height() - 50);
        }
    }
    return;
}
window.currentUrl = '';
/**
 * @date 2017-05-08
 * @desc
 */
function logout() {
    if (window.location.pathname == LOGOUT_URL) {
        return;
    }
    if ($('iframe[name=main]').length) {
        window.location = LOGOUT_URL + '?not-login=401';
    } else {
        if (window.parent) {
            if (window.parent.logout) {
                window.parent.logout();
            }
        }
    }
}
/**
 *  disable btn
 * @param $ele
 */
function disableBtn($ele) {
    if ($ele.length) {
        $ele.addClass("disabled");
        $ele.attr('disabled', true).prop('disabled', true);
        $ele.data('json', null)
    }
}
/**
 * enable btn
 * @param $ele
 */
function enableBtn($ele, $json) {
    if ($ele.length) {
        $ele.removeClass("disabled");
        $ele.attr('disabled', false).prop('disabled', false);
        if ($json) {
            $ele.data('json', $json);
        }
    }
}
/**
 * @date 2017-05-09
 * @desc 驼峰转下划线
 */
function camelTo(s) {
    if (!s) {
        return '';
    }
    s = s || "fooStyleCss";
    s = s.replace(/([A-Z])/g, "_$1").toLowerCase();
    return s;
}

/**
 * 父页面和子页都需要调用此方法，父页面先行请求，
 * 如何保证在父页面请求执行期间，子页面的调用
 * 直接获取父页面请求后的结果
 * @returns {*}
 */
function getLoginUser() {
    var dtd = $.Deferred();
    if (!!MANAGER_CURRENT) { // 直接返回当前数据
        dtd.resolve(MANAGER_CURRENT);
    } else {
        if (!LOADING_USER) {
            LOADING_USER = true;
            $.get('/user/get_current', function (data) {
                if (data.code == 200) {
                    MANAGER_CURRENT = data.data;
                    dtd.resolve(data.data);
                } else {
                    ;
                    dtd.reject(data.error)
                }
                LOADING_USER = false;
            });
        } else {
            //暂行解决方法
            // console.log('方法已经执行，正在等待结果!')
            var inter = setInterval(function () {
                if (!!MANAGER_CURRENT) {
                    dtd.resolve(MANAGER_CURRENT);
                    clearInterval(inter);
                    console.log('等待结果:' + MANAGER_CURRENT)
                }
            }, 100);
        }
    }
    return dtd.promise();
}
/***
 * 获取登录用户某一前缀
 * @param permissionP
 */
function getUserPermission(permissionPrefix) {
    var dtd = $.Deferred();
    if (window['permission' + permissionPrefix]) {
        // console.log(window['permission' + permissionPrefix]);
        dtd.resolve(window['permission' + permissionPrefix])
    }
    $.when(getLoginUser())
        .then(function (user) {
            var permission = _.filter(user.permissions, function (item) {
                return item.url.indexOf(permissionPrefix) != -1;
            });
            permission = _.groupBy(permission, 'url');
            window['permission' + permissionPrefix] = permission;
            // console.log(permission);
            dtd.resolve(permission);
        })
        .fail(function (e) {
            console.log(e);
            dtd.reject(e);
        });
    return dtd.promise();
}
/**
 *
 * @param 获取登录用户公章
 * @returns {*}
 */
function getUserSignature() {
    var dtd = $.Deferred();
    $.get('/user/getSignature', function (res) {
        if (res.code == 200) {
            dtd.resolve(res.data);
        } else {
            dtd.reject(res)
        }
    });

    return dtd.promise();
}

/**
 * 判断当前某个功能模块  S:销售(默认),C:采购, P:发票
 */
function judgeCertainModule() {
    if ($.cookie) {
        return $.cookie(MODULE_) || 'CRM';
    } else {
        return 'CRM';
    }

}
function setCurrentModule(modale_) {
    $.cookie(MODULE_, modale_); // S:销售(默认),C:采购, P:发票
    window.location.reload();
}
function initModuleLabel() {

    var scp = judgeCertainModule(), $currentModule = $('.module-nav');
    $('.module-nav').find('#menu' + scp).addClass('active');
    if ($('.module-nav li.active').length) {
        var menus = $('.module-nav li.active a').text();

        $('.nav-bread-su').closest('ol').html('<li>' +
            '<a href="/admin/main.html"><span class="icon-home" style="margin-right: 9px;color: #28a3ef;" ></span> 首页</a>»</li><li><span>' + menus + '</span>»</li><li><span >' +
            $(top.parent.document).find('.treeview.active > a span').text() + '</span>»</li><li><a href="/admin' +
            ( $(top.parent.document).find('.treeview.active .active a').attr('href') ? $(top.parent.document).find('.treeview.active .active a').attr('href').substr(1) : '-') + '">' + $(top.parent.document).find('.treeview.active .active').text() + '</a></li>')
    }
}
function initMenuByModule() {
    $.when(parent.getLoginUser(), getMenusList(), getMenusItemList())
        .then(function (data, menus, menuItems) {
            // menus = menus.list;
            menuItems = menuItems.list;
            if ($('.user-name').length) {
                $('.user-name').html(data.name);
            }
            var permission = _.filter(data.permissions, function (item) {
                return item.type == 1;
            });
            var pres = _.groupBy(permission, 'id');
            var group_permission = _.groupBy(permission, function (item) {
                if (item.url.indexOf('./gat') == 0 || item.url.indexOf('./due') == 0 || item.url.indexOf('./inv') == 0 || item.url.indexOf('./rec') == 0) {
                    return item.url.slice(0, 5);
                }
                return item.url.slice(0, item.url.lastIndexOf('/'));
            });
            var scp = judgeCertainModule(), $currentModule = $('.module-current');
            menus = _.filter(menus, function (item) {
                return item.level == 2;
            });
            menus = _.groupBy(menus, 'pId');
            menuItems = _.groupBy(menuItems, 'categoryId');
            if (menus[scp] && menus[scp].length) {
                _.sortBy(menus[scp], 'orderNum').map(function (item) {
                    var cus_menus = '<li class="treeview "> \
                        <a href="#"> \
                        <i class="icon-codepen"></i> <span>' + item.name + '</span> \
                        <span class="pull-right-container"> \
                        <i class="icon icon-chevron-left pull-right"></i> \
                        </span> \
                        </a> \
                        <ul class="treeview-menu"> ';

                    var cus_menus_status = false;
                    if (menuItems[item.id] && menuItems[item.id].length) {
                        menuItems[item.id].map(function (item) {
                            if (pres[item.itemId] && pres[item.itemId].length) {
                                var t = pres[item.itemId][0];
                                cus_menus_status = true;
                                cus_menus += '<li><a href="' + t.url + '" target="main"><i class="icon-radio-unchecked"></i> ' + t.permissionName + '</a></li>';
                            }
                        })
                    }
                    if (cus_menus_status) {
                        cus_menus += '</ul></li>';
                        $('.sidebar-menu').append(cus_menus);
                    }
                });
            }
            initMenu();

        })
        .fail(function (e) {
            console.log('接口错误-：' + e)
        });
}


var Provider = {
    /***
     * 单条数据应付
     * @param item
     * @returns {*}
     */
    itemPayable: function (item) {
        if (item.type == 2) {
            return 0;
        }
        if (item.type == 9) {
            return 0;
        }
        if (item.type == 5) {
            return 0;
        }
        return item.totalDeposit;
    },
    /**
     *  单条数据实付
     * @param item
     * @returns {*}
     */
    itemNetPay: function (item) {
        if (item.type == 2) {
            return item.totalDeposit;
        }
        if (item.type == 9) {
            return item.totalDeposit;
        }
        if (item.type == 5) {
            return -item.totalDeposit;
        }
        return 0;
    }
};
var Clientele$ = {
    /***
     * 单条数据应付
     * @param item
     * @returns {*}
     */
    itemReceivable: function (item) {
        if (item.type == 0)return 0;
        if (item.type == 8)return item.totalDeposit;
        return 0;
    },
    /**
     *  单条数据实付
     * @param item
     * @returns {*}
     */
    itemNetReceive: function (item) {
        if (item.type == 0)return item.totalDeposit;
        if (item.type == 8)return 0;
        return 0;
    }
};

function initMenu() {
    var $slider = $('.sidebar');
    if ($slider.length) {
        $slider.find('li.treeview').click(function (e) {
            var t = $(e.target).closest('li');
            t.children('a').find('span i').removeClass('icon-chevron-left').addClass('icon-chevron-down');
            t.addClass('active').siblings('li').removeClass('active');
            t.siblings('li').children('a').find('  span > i').removeClass('icon-chevron-down').addClass('icon-chevron-right');
        });
    }
    initMenuEvent();
}
function initMenuEvent() {
    $('.treeview-menu > li > a').click(function () {
        if (window.currentUrl == $(this).attr('href')) {
            return false;
        }
        window.$loading.fadeIn();
        window.currentUrl = $(this).attr('href');
        var scp = judgeCertainModule();

        $.cookie(CURRENT_ROUTER + scp, window.currentUrl);
        if (window.location.hostname == 'localhost') { //debug modal
            NProgress && NProgress.start();
            // $(this).attr('href', $(this).attr('href') + '?' + Math.random());
            $(this).attr('href', $(this).attr('href'));
            //return true;
            if (!$(this).closest('.treeview').hasClass('active')) {
                $(this).closest('.treeview').siblings('li').removeClass('active');
                $(this).closest('.treeview').addClass('active');
            }
        }
        return true;
    });
    initFromCookie();
}
function initFromCookie() {
    if ((window.location.pathname == '/admin/index.html') || (window.location.pathname == '/index.html')) {
        var searchObj = parseSearch();
        CURRENT_ROUTER += searchObj.id || '';
    }
    var scp = judgeCertainModule();
    if ($.cookie && $.cookie(CURRENT_ROUTER + scp)) {
        var current = $.cookie(CURRENT_ROUTER + scp);
        if (current) {
            var $current = $('[href="' + current + '"]');
            $current.closest('li').addClass('active');
            $current.closest('.treeview').click();
            return window.frames['main'] && (window.frames['main'].location = '/admin/' + current.substr(2)); //update at 2017-02-23 08:51
        }
    }
    return window.frames['main'] && (window.frames['main'].location = '/admin/main.html');
}

function getDomain() {
    return window.location.host
    // return $('meta[name=domain]', window.parent.document).attr('content');
}

/**
 *
 * 获取所有用户
 * @returns {*}
 */
function getAllUsers() {
    var dtd = $.Deferred();
    if (!!FETCH_DATA.USERS) { // 直接返回当前数据
        dtd.resolve(FETCH_DATA.USERS);
    } else {
        if (!FETCH_STATUS.USERS) {
            FETCH_STATUS.USERS = true;
            $.get('/user/all?size=500', function (data) {
                if (data.code == 200) {
                    FETCH_DATA.USERS = _.groupBy(data.list, 'id');
                    dtd.resolve(FETCH_DATA.USERS);
                } else {
                    dtd.reject(data.error)
                }
                FETCH_STATUS.USERS = false;
            });
        } else {
            //暂行解决方法
            var inter = setInterval(function () {
                if (!!FETCH_DATA.USERS) {
                    dtd.resolve(FETCH_DATA.USERS);
                    clearInterval(inter);
                }
            }, 100);
        }
    }
    return dtd.promise();
}
function getLastDay(year, month) {
    console.log(arguments);
    var new_year = year;  //取当前的年份  
    var new_month = month++;//取下一个月的第一天，方便计算（最后一天不固定）  
    if (month > 12)      //如果当前大于12月，则年份转到下一年  
    {
        new_month -= 12;    //月份减  
        new_year++;      //年份增  
    }
    var new_date = new Date(new_year, new_month, 1);        //取当年当月中的第一天  
    return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();//获取当月最后一天日期  
}
function generateExportUrl(str) {
    window.parent.location = window.location.origin + '/api/admin' + str.replace('query', 'export');
}
var One_Day = 60 * 60 * 24 * 1000;
function getMonthBeginAndEnd(objDate) {
    var date = new Date(objDate || Date.now());
    return {
        // start: moment(Date.now()).format('YYYY-MM-01'),
        start: moment(Date.now() - 60 * One_Day).format('YYYY-MM-DD'),
        end: moment(Date.now()).format('YYYY-MM-DD'),
        // end: moment().format('YYYY-MM-' + getLastDay(date.getYear()
        //         , date.getMonth())),
    }
}
/**
 * 初始化查询条件
 */
function initSearch(query) {
    if (query == undefined)return;
    console.log('query==' + JSON.stringify(query));
    Object.keys(query).map(function (item) {
        var $item = $('[name=' + item + ']');
        if ($item.length == 1) {
            $item.val(query[item])
        }
    });
}
/**
 *  存取或初始化查询条件
 * @param obj
 */
function searchInputValue(key, obj) {
    try {
        if (LS == undefined)return;
    } catch (e) {
        return;
    }
    if (obj == undefined) {
        var jsonObj = LS.json(md5(window.location.href.split('?')[0] + (key || '')));
        if (jsonObj != undefined && !!jsonObj.saveTime) {
            //console.log(Date.now() + '-' + (jsonObj.saveTime) + '=' + (Date.now() - parseInt(jsonObj.saveTime)) + '(Date.now() - parseInt(jsonObj.saveTime)) > 1000 * 60*3=' + (!!((Date.now() - parseInt(jsonObj.saveTime)) > 1000 * 5)))
            if ((Date.now() - parseInt(jsonObj.saveTime)) > 1000 * 60 * 3) { // 相隔3*60s钟
                jsonObj = {};
            }
            delete jsonObj.saveTime;
            initSearch(jsonObj);
        }
        return jsonObj || {};
    } else {
        obj.saveTime = Date.now();
        LS.json(md5(window.location.href.split('?')[0] + (key || '')), (obj));
    }
};
function lsSet(key, val) {
    key = md5(window.location.href.split('?')[0] + key);
    LS.json(key, val);
}
function lsGet(key) {
    key = md5(window.location.href.split('?')[0] + key);
    var jsonObj = LS.json(key);
    return jsonObj || {};
}
function location_(url, key) {
    var query = getToolBarSearch();
    searchInputValue(key || 'search', query);
    window.location = url;
}
/**
 *  获取.toolbar中text、select查询对象
 * @returns {{}}
 */
function getToolBarSearch() {
    var $toolbar = '', query = {};
    if ($('.search-senior').length && $('.search-senior').css('display') == 'block') {
        $toolbar = $('.search-senior');
    } else if ($('.toolbar').length && $('.toolbar').css('display') == 'block') {
        $toolbar = $('.toolbar');
    }
    if (window.location.href.indexOf('store/express') > -1) { // 发货特殊处理
        $('.toolbar').find('select,input[type=text]').each(function (index, item) {
            if ($(item).attr('name') != 'undefined') {
                query[$(item).attr('name')] = $(item).val();
            }
        })
    }
    if ($toolbar.length) {
        $toolbar.find('select,input[type=text]').each(function (index, item) {
            if ($(item).attr('name') != 'undefined') {
                query[$(item).attr('name')] = $(item).val();
            }
        });
    }

    return (query) || {};
}
function getLocation(key) {
    return window.location.href.split('?')[0] + (key || '');
}
function getUrlMd5(key) {
    return md5(getLocation(key));
}
/**
 *  获取通过URL的md5值缓存的对象
 * @returns {*|{}}
 * @key 可选 ：url 追加的字符
 */
function getTmpObj(key) {
    var obj = window[getUrlMd5(key)] || {};
    // console.log('缓存查询条件====' + JSON.stringify(obj));
    return pureObj(obj);
}

function getDomainAndPort() {
    return window.location.hostname + (window.location.port ? ":" + window.location.port : "");
}

/**
 * obj.isForce 是否强制请求，obj.isExport 是否导出,obj.url 查询url，obj.query 查询条件
 * @param obj
 * @param userAction 是否用户行为，true 用户行为，不需要对查询条件净化，否则需要对查询条件净化，即为空的字段使用上次查询条件
 * @returns {string}
 */
function gSearch(obj, userAction) {
    if (obj == undefined)return;
    var query_ = getToolBarSearch(); // 当前状态查询条件
    var KEY_HANDLER_STATUS = obj.url + '-status';//本页请求key
    var KEY_PREV_CONDITION_STATUS = obj.url + '-prev-condition';//本功能最后一次查询条件暂存
    //var KEY_TEMP_CONDITION_STATUS = obj.url + '-temp-condition';//本页最后一次查询条件暂存
    if (window[KEY_HANDLER_STATUS]) return fnInfo("处理中...,请等待");
    if (window[KEY_HANDLER_STATUS] == false) window[KEY_HANDLER_STATUS] = true;
    var currentQuery = $.extend({}, {page: 1, size: 15, timestamp: new Date().getTime()}, query_, obj.query || {});//
    var lastCondition = lsGet(KEY_PREV_CONDITION_STATUS);
    if (!compareQuery(currentQuery, lastCondition)) {  //扣除page,size,timestamp之外的查询参数是否一致，不一致则从第一页计算
        currentQuery.page = 1; // 除分页外，和上次查询信息是不一致，从第一页开始查询
    }

    var sizeObj = obj.query && obj.query.size ? {size: obj.query.size} : {size: lastCondition.size || currentQuery.size};//优先使用用户选择的size，如果没有则使用最后一次查询条件的size，再否则默认size
    var pageObj = obj.query && obj.query.page ? {page: obj.query.page} : {page: lastCondition.page || currentQuery.page};//优先使用用户选择的page，如果没有则使用最后一次查询条件的page，再否则默认page
    currentQuery = $.extend({}, lastCondition, currentQuery, sizeObj, pageObj);
    $('.search-btn').length && $('.search-btn').button('loading');
    var arg = [];
    Object.keys(currentQuery).map(function (key) {//
        if ((currentQuery[key] + '').length) {
            arg.push(key + '=' + currentQuery[key]);
        }
    });
    if (obj.isExport) {
        window[getUrlMd5(KEY_HANDLER_STATUS)] = false;
        $('.search-btn').length && $('.search-btn').button('reset');
        return (obj.url.indexOf('?') > -1 ? obj.url : (obj.url + '?')) + arg.join('&');
    }
    return $.get((obj.url.indexOf('?') > -1 ? obj.url + '&' : (obj.url + '?')) + arg.join('&'), function (res) {
        lsSet(KEY_PREV_CONDITION_STATUS, currentQuery);
        window[getUrlMd5(KEY_HANDLER_STATUS)] = false;
        $('.search-btn').length && $('.search-btn').button('reset');
        if (res.code != 200) {
            return (res.error);
        }
        if ((res.list.list && res.list.list.length) || res.list.length) {
            searchInputValue(KEY_PREV_CONDITION_STATUS, currentQuery);
            obj.render(res.list.list || res.list, {
                lastSearchKey: KEY_PREV_CONDITION_STATUS
            });
        } else {
            if (obj.table) {
                obj.render([], {
                    lastSearchKey: KEY_PREV_CONDITION_STATUS
                });
            } else {
                searchInputValue(KEY_PREV_CONDITION_STATUS, currentQuery);
                obj.render(noData(), {
                    lastSearchKey: KEY_PREV_CONDITION_STATUS
                });

            }
        }
        var page = res.page || res.list;
        pageInit(page, $.extend({}, obj, {
            query: getTmpObj('search')
        }), gSearch)

    });
}
$(function () {
    var $dateRange = $('.filter-conditation');
    if ($dateRange.length) {
        var date = new Date();
        $dateRange.find('[name=startDate]').val(getMonthBeginAndEnd().start);
        $dateRange.find('[name=endDate]').val(getMonthBeginAndEnd().end);

    }
    // jQuery.ajaxSettings.traditional = true;
    // 设置jQuery Ajax全局的参数
    $.ajaxSetup({
        dataType: 'json',
        type: "GET",
        cache: false,
        complete: function (xhr, status) {
            if (this.url.indexOf('/templets') == 0) {

                // cb(data);
            } else if (xhr.responseText && this.url.indexOf('http://') != 0) {
                xhr.responseJSON = JSON.parse(xhr.responseText);
                if (xhr.responseJSON && xhr.responseJSON.code == 401) {
                    logout();
                }
                try {
                    if (xhr.response && typeof xhr.response == 'string') {
                        var res = JSON.parse(xhr.response);
                        if (res && res.code == 401) {
                            logout();
                        }
                    }
                } catch (e) {
                    console.log(e)
                }
            }

        },
        error: function (jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
                case(500):
                    alert("服务器系统内部错误");
                    break;
                case(401):
                    logout();
                    alert("未登录");
                    break;
                case(403):
                    alert("无权限执行此操作");
                    break;
                case(408):
                    alert("请求超时");
                    break;
                default:
                // alert("未知错误");
            }
        },
        success: function (data) {

            // alert("操作成功");
        },
        beforeSend: function (xhr, request) {

            // var ignore = '/path-cut-image-oss|', prefix = '';
            var ignore = '/path-cut-image|', prefix = '';
            if (request.url.indexOf('templets') > -1) {
                prefix = '/admin';
                request.dataType = 'xml';
            } else if (ignore.indexOf(request.url) > -1) {
                prefix = (window.location.hostname == 'localhost' ? '/api/' : '/api/');
            } else {
                prefix = (window.location.hostname == 'localhost' ? '/api/admin' : '/api/admin');
            }
            if (!request.url.indexOf('http://') == 0 && !request.url.indexOf('https://') == 0) {
                request.url = prefix + request.url;
            } else {
                request.dataType = 'html';
            }
        }
    });
    $.ajaxSetup({
        type: "POST",
        dataType: 'json',
        cache: false,
        contentType: 'application/x-www-form-urlencoded',
        complete: function (xhr, status) {
            if (this.url.indexOf('/templets') > -1) {

            } else if (xhr.responseText && this.url.indexOf('http://') != 0) {
                xhr.responseJSON = JSON.parse(xhr.responseText);
                if (xhr.responseJSON && xhr.responseJSON.code == 401) {
                    logout();
                }
                try {
                    if (xhr.response && typeof xhr.response == 'string') {
                        var res = JSON.parse(xhr.response);
                        if (res && res.code == 401) {
                            logout();
                        }
                    }
                } catch (e) {
                    console.log(e)
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
                case(500):
                    alert("服务器系统内部错误");
                    break;
                case(401):
                    logout();
                    alert("未登录");
                    break;
                case(403):
                    alert("无权限执行此操作");
                    break;
                case(408):
                    alert("请求超时");
                    break;
                default:
                // alert("未知错误");
            }
        },
        success: function (data) {
            // alert("操作成功");
        },
        beforeSend: function (xhr, request) {
            // if (request.data && request.url.toLowerCase().indexOf('paper') == -1) { //
            //     var json = parseSearch(request.data), args = [];
            //     Object.keys(json).map(function (key) {
            //         if (key != 'batchNum') {
            //             json[key] = json[key].replace('+', '').replace('%2d', '-').replace('%20', ''); //
            //         }
            //         args.push(key + '=' + encodeURI(json[key]));
            //     });
            //     request.data = args.join('&');
            // }
            // var ignore = '/path-cut-image-oss|', prefix = '';
            var ignore = '/path-cut-image|', prefix = '';
            if (request.url.indexOf('templets') > -1) {
                prefix = '/admin';
                request.dataType = 'xml';
            } else if (ignore.indexOf(request.url) > -1) {
                prefix = (window.location.hostname == 'localhost' ? '/api/' : '/api/');
            } else {
                prefix = (window.location.hostname == 'localhost' ? '/api/admin' : '/api/admin');
            }
            if (!request.url.indexOf('http://') == 0 && !request.url.indexOf('https://') == 0) { //
                request.url = prefix + request.url;
            } else {
                request.dataType = 'html';
            }
        }
    });
    getUnRead();
    if ($('.select_dispatch').length) {
        $('.select_dispatch').focus(function () {
            $(this).siblings('.select_multi').fadeIn().find('.btn').click(function () {
                $(this).closest('.select_multi').fadeOut();
            });
        });
    }
    sysInit();
    if ($('.table-responsive').length) {
        ($('.table-responsive').perfectScrollbar && $('.table-responsive').perfectScrollbar());
    }
    renderBtn();
    $('.body').delegate('.opt-more', 'click', function () {
        var self = this;
        $(this).closest('td').find('.operate-area').toggle();
    });
    $('.body').delegate('.operate-area', 'blur', function () {
        $(this).toggle();
    });
    initIframe();
    /**
     * 全局阻止冒泡
     */
    $('.no-pop').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        return false;
    });
    $(window).resize(function () {
        initIframe();
    });

    if ($('.main-sidebar').length) {
        initMenuByModule();
    } else if (window.location.href.indexOf('login.html') > -1) {
        var searchObjLogin = parseSearch();
        if (!searchObjLogin['not-login']) {
            $.get('/user/get_current', function (data) {
                if (data.code == 200) {
                    data = data.data;
                    window.location = '/admin/index.html?id=' + data.id
                } else {

                }
            });
        }
    } else { // sub page
        searchInputValue();
        // window.currentUrl = window.location.href;
        // window.currentUrl = '.'+window.currentUrl.split('/admin')[1]
        // var scp  = parent.window.judgeCertainModule();
        // $.cookie(CURRENT_ROUTER+scp, window.currentUrl);

        /**
         * ref: https://www.cnblogs.com/xianyulaodi/p/5035171.html
         */
        // window.onbeforeunload = function () {return false;}
        // window.onunload = function () {
        //     console.log("你确定要离开");
        // }

    }


    $('.table .interactive').click(function (e) {
        $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
    });

    $('.sidebar-toggle').click(function () {
        if ($('body').hasClass('sidebar-collapse')) {
            $('body').removeClass('sidebar-collapse')
        } else {
            $('body').addClass('sidebar-collapse')
        }
    });
    //logout
    if ($('.logout').length) {
        $('.logout').click(function () {
            $.get('/user/logout', function (data) {
                logout();
                // window.location.href = LOGOUT_URL;
            })
        })
    }
    if (parent.window.initModuleLabel && window.location.href.indexOf('/login.html') == -1 && window.location.href.indexOf('/print.html') == -1) {
        parent.window.initModuleLabel && parent.window.initModuleLabel();
    }


});
/***
 * 异步请求json转查询字符串生成器
 */
function ajaxArgStrGenerator(query) {
    query = query || {};
    var arg = [];
    Object.keys(query).map(function (key) {
        if ((query[key] + '').length && query[key] != null) { // 过滤值为 "" 和null 字段
            arg.push(key + '=' + query[key])
        }
    });
    return arg.join('&');
}
/**
 * 查询条件
 * @param query1
 * @param query2
 */
function compareQuery(query1, query2) {
    var init1 = {page: '', timestamp: '', size: ''};
    if (parseInt(query1.page) != NaN && parseInt(query2.page) != NaN && parseInt(query1.page) >= 1 && parseInt(query2.page) >= 1 && parseInt(query1.page) != parseInt(query2.page)) {
        return true;
    }
    return _.isEqual(pureObj($.extend({}, query1, init1)), pureObj($.extend({}, query2, init1)));
}
/**
 *  净化 值为 undefined,'',null 的字段或字段名为undefined将从对象中删除值
 * @param obj
 */
function pureObj(obj) {
    if (!obj)return {};
    var newObj = {};
    Object.keys(obj).map(function (key) {
        if (key != 'undefined' && obj[key] && (obj[key]) != 'undefined') {
            newObj[key] = obj[key];
        }
    });
    return newObj;
}
/**
 * 判断两个对象
 * @param obj1
 * @param obj2
 */
function isSameQueryStr(obj1, obj2) {
    obj1 = pureObj(obj1);
    obj2 = pureObj(obj2);
    if (!obj1 || !obj1) {
        return false;
    }
    if (_.isEmpty(obj1) || _.isEmpty(obj2)) {
        return false;
    }
    if (obj2.timestamp) {
        obj1.timestamp = obj2.timestamp; ///  时间戳保持一致
    } else {
        obj2.timestamp = obj1.timestamp; ///  时间戳保持一致
    }
    // if(obj2.timestamp)
    var res = _.isEqual(obj1, obj2);
    if (res) {
        if ((Date.now() - obj2.timestamp) < 2000) {
            fnFail("相同查询条件的请求，请两次操作间隔时间大于2秒"); //
            return true;
        }
    }
    return false;
}


/**
 * 无当前年份的日期时间格式化
 * @param data
 * @returns {*}
 */
function formatTimeStrWithoutYear(data) {
    var date = new Date(data), now_ = new Date();
    if (date.getFullYear() == now_.getFullYear()) {
        return moment(data).format('MM-DD HH:mm:ss')
    } else {
        return moment(data).format('YYYY-MM-DD HH:mm:ss')
    }
}
/**
 * 无当前年份日期格式化
 * @param data
 * @returns {*}
 */
function formatDateStrWithoutYear(data) {
    var date = new Date(data), now_ = new Date();
    if (date.getFullYear() == now_.getFullYear()) {
        return moment(data).format('MM-DD')
    } else {
        return moment(data).format('YYYY-MM-DD')
    }
}
function formatDate(data) {
    var date = new Date(data || Date.now());
    return date.getFullYear() + '-' + ((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '-' + (date.getDate() > 9 ? date.getDate() : ('0' + date.getDate()));
}
function formatTime(data) {
    var date = new Date(data);
    return date.getFullYear() + '-' + ((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '-' +
        (date.getDate() > 9 ? date.getDate() : ('0' + date.getDate())) + ' ' +
        (date.getHours() > 9 ? date.getHours() : ('0' + date.getHours())) + ':' +
        (date.getMinutes() > 9 ? date.getMinutes() : ('0' + date.getMinutes())) + ':' +
        (date.getSeconds() > 9 ? date.getSeconds() : ('0' + date.getSeconds()));
}
try {
    if (Handlebars) {
        /**
         * 转换审核状态
         */
        Handlebars.registerHelper("tfCheckStatus", function (value) {
            if (value == 0) {
                return "未审核";
            } else if (value == 1) {
                return "审核通过";
            } else if (value == 2) {
                return "审核未通过";
            } else {
                return '';
            }
        });
        Handlebars.registerHelper('tfLadingBillType', function (value) {
            return value == '0' ? '车号' : (value == '1' ? '转货权' : (value == '2' ? '介绍信' : ''));
        });
        Handlebars.registerHelper('tfMillisecond', function (value) {
            return moment(value).format('YYYY/MM/DD');
        });
        Handlebars.registerHelper('juadge', function (value) {
            if (value == 0) {
                return "管理人员发货";
            } else {
                return "客户发货";
            }
        });
    }
} catch (e) {
    ///console.log(e.stack)
}
function tfCheckStatus(value) {
    if (value == 0) {
        return "<span class='tag tag-warning'>未审核</span>";
    } else if (value == 1) {
        return "<span class=' tag  tag-success'>审核通过</span>";
    } else if (value == 2) {
        return "<span class=' tag  tag-danger'>审核未通过</span>";
    } else {
        return '';
    }
}
function tfLadingBillType(value) {
    return value == '0' ? '车号' : (value == '1' ? '转货权' : (value == '2' ? '介绍信' : ''));
}


/**
 * 提现状态
 * @param status
 * @returns {*}
 */
function generateWithDrawStatusLabel(status){
    if(status==1){return '待审核'}
    if(status==2){return '审核拒绝'}
    if(status==3){return '待打款'}
    if(status==4){return '已完成'}
    return '';
}
function juadge(value) {
    if (value == 0) {
        return "管理人员发货";
    } else {
        return "客户发货";
    }
}
/**
 *     //  材料准备阶段2-材料提交阶段3，国家审核中4-出证5/驳回6-完成8

 *  订单状态对应提示
 * @param status
 * @returns {{status: *, text: string}}
 */
function orderStatus(status) {
    var text = '';
    if (status == 0) {
        text = '执行'
    } else if (status == 1) {
        text = '执行'
    } else if (status == 2) {
        text = '材料准备阶段'
    } else if (status == 3) {
        text = '材料提交阶段'
    } else if (status == 4) {
        text = '国家审核中'
    } else if (status == 5) {
        text = '出证'
    } else if (status == 6) {
        text = '驳回'
    } else if (status == 8) {
        text = '完成'
    } else if (status == '-2') {
        text = '超时未付款取消'
    } else if (status == '-1') {
        text = '取消[付款回退]'
    }
    return {
        status: status,
        text: text
    }
}
function RunOnBeforeUnload() {
    if ($('iframe[name=main]') && $('iframe[name=main]').length) {
        // if (confirm(("确认退出系统？"))) {
        //     window.event.returnValue = '关闭浏览器将退出系统.';
        // }
    }


}
function RunOnUnload() {
    //执行你的代码
//在这里处理你的保存数据，清除cookies等操作
    if ($('iframe[name=main]') && $('iframe[name=main]').length) {

    }
}
function orderPayMethod(status) {
    var text = '';
    if (status == 0) {
        text = '银行电汇'
    } else if (status == 1) {
        text = '承兑汇票'
    } else if (status == 2) {
        text = '国内信用证'
    }
    return {
        payMethod: status,
        text: text
    }
}
/**
 * 设置每页显示多少条数据
 * @returns {string}
 */
function generatePageSize(size, total) {
    if (!size) {
        size = 1;
    }
    return '<div style="float: left;">每页显示 <select class="size-select"><option ' + (size == 15 ? 'selected' : '') + ' value="15">15</option><option  '
        + (size == 35 ? 'selected' : '') + '  value="35">35</option><option  ' + (size == 90 ? 'selected' : '') + '  value="90">90</option></select> 条。' + (total ? ('共' + total + '条') : '') + '</div>'
}
function initSubPageScroll() {
    var $window = $(window);
    var $toolbar = $('.toolbar');
    if ($toolbar && $('.sub-body').length) {
        $window.scroll(function () {
            var $toolbar = $('.toolbar'), defaultHeight = 50;
            if ($toolbar.length) {
                defaultHeight = $toolbar.closest('div.panel-body').offset().top - 10;
            }
            console.log(defaultHeight);
            if ((defaultHeight) <= $window.scrollTop()) {
                $toolbar.addClass('toolbar-fixed')
            } else if ($window.scrollTop() < defaultHeight) {
                $toolbar.removeClass('toolbar-fixed');
            }
        });
    }
}
function noData(num) {
    if (!num) {
        //throw new Error('无数据参数不合法!')
        num = $('.table-responsive').find('thead').find('th').length;
    }
    return '<tr><td colspan="' + num + '" style="text-align: center;font-size: 12px;">没有找到符合查询条件的数据!</td></tr>';
}


var VALIDATION_SETTING = {
    framework: 'bootstrap',
    locale: 'zh_CN',
    icon: {
        required: 'fa fa-asterisk',
        valid: 'fa fa-check',
        invalid: 'fa fa-exclamation-circle',
        validating: 'fa fa-refresh'
    },
    err: {
        container: 'tooltip'
    },
}, EJS_SETTING = {
    open: '{{',
    close: '}}'
}, dateSetting = {
    size: 'small',
}, MULTI_SETTING = {
    dropRight: true,
    maxHeight: 200,
    buttonWidth: 200,
    disableIfEmpty: true,
    enableFiltering: true,
    includeSelectAllOption: false,
    nonSelectedText: '请选择!',
    selectAllText: '全选',
    filterPlaceholder: '搜索',
    nSelectedText: '已选择',
    allSelectedText: '已选择全部',
    disabledText: 'Disabled ...',
    onChange: function (option, checked) {
        // alert(option.length + ' options ' + (checked ? 'selected' : 'deselected'));
    },
    onDropdownHide: function (event) {
        // alert('Dropdown closed.');
        // alert($multi.getSelected());
    }
}, TABLE_SETTING = {
    checkbox: true, // 是否显示复选框
    radio: false, //是否显示单选框
    seqNum: true, // 是否显示序号
    showSearchComplex: false,/// 是只显示复杂搜索框
    multiSelect: false, //默认不可多选行
    fixedHeader: true,//显示时固定表头
    onlyBody: false,
    sort: function () {
    }, //排序回调函数
    destroyBtn: function () {
    }, //禁用按钮
    createBtn: function () {
    }, // 启用她扭
    toolbar: '.toolbar',
    enableSetting: true,//允许自定义显示列

};
function mergeEjsSetting(setting) {
    return $.extend({}, EJS_SETTING, setting || {})
}
try {
    if (ejs) {
        ejs.delimiter = '$';
        ejs._with = false;
    }
} catch (e) {
    //console.log(e.stack)
}
function notice(content) {
    if (window.frames['main']) {
        if (window['main'] && window['main'].window.notice) {
            return window['main'].window.notice(content);
        } else {
            setTimeout(function () {
                notice(content);
            }, 1000)
            return;
        }
        // getDataByUrl()
        // return;
    }
    var html = $.ajax({
        type: 'GET',
        url: 'http://' + getDomain() + '/admin/templets/notice.html', async: false
    });
    if ($('.notice').length) {
        $('.notice p').html('【新消息】' + content);
        $('.notice').alert();
    } else {
        $('body').append(ejs.render(html.responseText
            , {content: content}))
    }
}
function tableSelect($table, destroyBtn, createBtn) {
    $table.find('tbody tr').unbind('click').click(function () {
        if ($(this).hasClass('active')) {
            destroyBtn && destroyBtn();
            $(this).removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
        } else {
            createBtn && createBtn(this);
            $(this).addClass('active').find('td:first-child input[type=checkbox]').attr('checked', true).prop('checked', true)
                .closest('tr').siblings('tr').removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
        }
    })
}

/**
 * table sort
 * @param $table
 * @param search
 */
function tableSort($table, search) {
    $table.find('th .fa').unbind('click').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search && search(sort);
    })

}

function _alert(alertConfig) {

    // 弹层静态方法，用于很少重复，不需记住状态的弹层，可方便的直接调用，最简单形式就是$.alert('我是alert') 或$.confirm('我是confirm') 或 $.confirm(options)
    //  若弹层内容是复杂的Dom结构， 建议将弹层html结构写到模版里，用$(xx).modal(options) 或无js的方式调用
    //
    //  example
    //  一下参数均可以data-xx 的形式在无js调用模式里配置在html模板.modal元素的data属性里(有些属性如okbtn cancelbtn没必要这么用，直接改html模板就行了)
    return $.alert($.extend({}, {
        title: '标题',
        body: 'html',// 必填
        okbtn: '确定',
        cancelbtn: '取消',
        closebtn: true,
        keyboard: false,   //是否可由esc按键关闭
        backdrop: 'static',//true  //决定是否为模态对话框添加一个背景遮罩层。另外，该属性指定'static'时，表示添加遮罩层，同时点击模态对话框的外部区域不会将其关闭。
        bgcolor: '#123456',  //背景遮罩层颜色
        width: 'normal',//{number|string(px)|'small'|'normal'|'large'} //推荐优先使用后三个描述性字符串，统一样式
        // timeout: {number} 1000    单位毫秒ms ,dialog打开后多久自动关闭
        // transition: {Boolean} 是否以动画弹出对话框，默认为true。HTML使用方式只需把模板里的fade的class去掉即可
        hasfoot: false,//{Boolean}  是否显示脚部  默认true
        // remote: {string} 如果提供了远程url地址，就会加载远端内容,之后触发loaded事件
        show: function (e) {

        },
        shown: function (e) {

        },
        hide: function () {

        },
        hidden: function () {

        },
        okHide: function (e) {
            // alert('点击确认后、dialog消失前的逻辑,
            // 函数返回true（默认）则dialog关闭，反之不关闭;若不传入则默认是直接返回true的函数
            // 注意不要人肉返回undefined！！')' +
        },
        cancelHide: function (e) {

        },
        cancelHidden: function (e) {
        }
    }, alertConfig || {}, {
        shown: function () {
            if (alertConfig.shown && !$('.modal-dialog').length) {
                alertConfig.shown();
            }
        }
    }));

}

function number_format(number, decimals, dec_point, thousands_sep) {
    /*
     * 参数说明：
     * number：要格式化的数字
     * decimals：保留几位小数
     * dec_point：小数点符号
     * thousands_sep：千分位符号
     * */
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.ceil(floatTool.multiply(n, k)) / k;
        };

    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

// document.write(number_format(222300400.123456))


$('body').delegate('.more', 'hover', function () {
    var $resp = $(this).closest('.table-responsive');
    if ($resp.length) {
        var $detail = $(this).find('.more-detail');
        if ($detail.length) {
            if ($detail.offset().top - $resp.offset().top > $detail.height() + 30) {
                $detail.addClass('up');
            }
        }

    }
});


function viewMore(str) {
    str = str || '';
    if (str.length <= 20) {
        return str;
    }
    return '<div class="view-more-ctner">' + str.substr(0, 20) + (str.length > 20 ? '...<a style="cursor: pointer;">查看</a>' : '') + '<div class="overflow-text">' + str + '</div></div>'
}
var FETCH_CACHE = {};

/**
 * 获取数据，如果已经获取，下次进入时从内存中读取
 * @param url
 * @param DATA_
 * @returns {*}
 */
function getDataByUrl(url, DATA_) {

    var dtd = $.Deferred();
    if (!FETCH_CACHE[DATA_]) { // undefined
        FETCH_CACHE[DATA_] = {DATA: '', STATUS: false};
    }
    if (!!FETCH_CACHE[DATA_].DATA) { // 直接返回当前数据
        dtd.resolve(FETCH_CACHE[DATA_].DATA);
    } else {
        if (!FETCH_CACHE[DATA_].STATUS) {
            FETCH_CACHE[DATA_].STATUS = true;
            $.get(url, function (data) {
                if (data.code == 200) {
                    FETCH_CACHE[DATA_].DATA = data.list;
                    dtd.resolve(FETCH_CACHE[DATA_].DATA);
                } else {
                    dtd.reject(data.error)
                }
                FETCH_CACHE[DATA_].STATUS = false;
            });
        } else {
            //暂行解决方法
            var inter = setInterval(function () {
                if (!!FETCH_CACHE[DATA_].STATUS) {
                    dtd.resolve(FETCH_CACHE[DATA_].DATA);
                    clearInterval(inter);
                }
            }, 100);
        }
    }
    return dtd.promise();
}

function getDataByUrlWithoutCache(url) {
    var dtd = $.Deferred();
    $.get(url, function (data) {
        if (data.code == 200) {
            dtd.resolve(data.list || data.data);
        } else {
            dtd.reject(data.error)
        }
    });
    return dtd.promise();
}

$('body').delegate('.panel', 'click', function (e) {
    if ($(e.target).siblings('.operate-area').length && $(e.target).siblings('.operate-area').css('display')) {
        $('.operate-area').hide();
        return $(e.target).siblings('.operate-area').show();
    }
    if (!$(e.target).closest('.operate-area').length && !$(e.target).hasClass('opt-detail') && !$(e.target).closest('.modal-dialog').length) {
        $('.operate-area').hide();
    }
})

/**
 * floatTool 包含加减乘除四个方法，能确保浮点数运算不丢失精度
 *
 * 我们知道计算机编程语言里浮点数计算会存在精度丢失问题（或称舍入误差），其根本原因是二进制和实现位数限制有些数无法有限表示
 * 以下是十进制小数对应的二进制表示
 *      0.1 >> 0.0001 1001 1001 1001…（1001无限循环）
 *      0.2 >> 0.0011 0011 0011 0011…（0011无限循环）
 * 计算机里每种数据类型的存储是一个有限宽度，比如 JavaScript 使用 64 位存储数字类型，因此超出的会舍去。舍去的部分就是精度丢失的部分。
 *
 * ** method **
 *  add / subtract / multiply /divide
 *
 * ** explame **
 *  0.1 + 0.2 == 0.30000000000000004 （多了 0.00000000000004）
 *  0.2 + 0.4 == 0.6000000000000001  （多了 0.0000000000001）
 *  19.9 * 100 == 1989.9999999999998 （少了 0.0000000000002）
 *
 * floatObj.add(0.1, 0.2) >> 0.3
 * floatObj.multiply(19.9, 100) >> 1990
 *
 */
var floatTool = function () {

    /*
     * 判断obj是否为一个整数
     */
    function isInteger(obj) {
        return Math.floor(obj) === obj
    }

    /*
     * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
     * @param floatNum {number} 小数
     * @return {object}
     *   {times:100, num: 314}
     */
    function toInteger(floatNum) {
        var ret = {times: 1, num: 0}
        if (isInteger(floatNum)) {
            ret.num = floatNum
            return ret
        }
        var strfi = floatNum + ''
        var dotPos = strfi.indexOf('.')
        var len = strfi.substr(dotPos + 1).length
        var times = Math.pow(10, len);
        var isFu = floatNum < 0;
        var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10)
        ret.times = times
        if (isFu) {
            ret.num = -intNum
        } else {
            ret.num = intNum
        }

        return ret
    }

    /*
     * 核心方法，实现加减乘除运算，确保不丢失精度
     * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
     *
     * @param a {number} 运算数1
     * @param b {number} 运算数2
     * @param digits {number} 精度，保留的小数点数，比如 2, 即保留为两位小数
     * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
     *
     */
    function operation(a, b, op) {
        var o1 = toInteger(a)
        var o2 = toInteger(b)
        var n1 = o1.num
        var n2 = o2.num
        var t1 = o1.times
        var t2 = o2.times
        var max = t1 > t2 ? t1 : t2
        var result = null
        switch (op) {
            case 'add':
                if (t1 === t2) { // 两个小数位数相同
                    result = n1 + n2
                } else if (t1 > t2) { // o1 小数位 大于 o2
                    result = n1 + n2 * (t1 / t2)
                } else { // o1 小数位 小于 o2
                    result = n1 * (t2 / t1) + n2
                }
                return result / max
            case 'subtract':
                if (t1 === t2) {
                    result = n1 - n2
                } else if (t1 > t2) {
                    result = n1 - n2 * (t1 / t2)
                } else {
                    result = n1 * (t2 / t1) - n2
                }
                return result / max
            case 'multiply':
                result = (n1 * n2) / (t1 * t2)
                return result
            case 'divide':
                return result = function () {
                    var r1 = n1 / n2
                    var r2 = t2 / t1
                    return operation(r1, r2, 'multiply')
                }()
        }
    }

    // 加减乘除的四个接口
    function add(a, b) {
        return operation(a, b, 'add')
    }

    function subtract(a, b) {
        return operation(a, b, 'subtract')
    }

    function multiply(a, b) {
        return operation(a, b, 'multiply')
    }

    function divide(a, b) {
        return operation(a, b, 'divide')
    }

    // exports
    return {
        add: add,
        subtract: subtract,
        multiply: multiply,
        divide: divide
    }
}();

function toFixed(num, s) {
    var times = Math.pow(10, s)
    var des = num * times + 0.5
    des = parseInt(des, 10) / times
    return des + ''
}

function fnFail(msg) {
    fnFail
    alert(msg || "操作失败!", "danger")
}

function fnSuccess(msg) {
    msgTips(msg || "操作成功!", "success")
}
function fnInfo(msg) {
    msgTips(msg || "操作成功!", "info")
}

function msgTips(text, style_) {
    bootoast({
        message: text || 'This is a danger toast message',
        type: style_ || 'danger',
        position: 'right-bottom',
        timeout: 3
    });
    // $.toast && $.toast(text, "" + style_, "top center");
}

/**
 * window.location.search to object
 * @returns {{}}
 */
function parseSearch(search) {
    var resultObj = {};
    var search = search || window.location.search;
    if (search && search.length > 1) {
        var search = search.indexOf('?') == 0 ? search.substring(1) : search;
        var items = search.split('&');
        for (var index = 0; index < items.length; index++) {
            if (!items[index]) {
                continue;
            }
            var kv = items[index].split('=');
            if (resultObj[kv[0]] != undefined) {
                if ($.isArray(resultObj[kv[0]])) {
                    // resultObj[kv[0]].push(decodeURI(kv[1])); // 解码
                    resultObj[kv[0]] += ',' + decodeURI(kv[1]);
                } else {
                    // var ar = [resultObj[kv[0]],decodeURI(kv[1])];
                    resultObj[kv[0]] += ',' + decodeURI(kv[1]);
                }
            } else {
                resultObj[kv[0]] = typeof kv[1] === "undefined" ? "" : decodeURI(kv[1]); // 解码
            }
        }
    }
    return resultObj;
}

function ajaxFileUpload(opt, cb) {
    $.ajaxFileUpload({
        // url: opt.url || '/api/uploadOss', //用于文件上传的服务器端请求地址
        url: opt.url || '/api/upload', //用于文件上传的服务器端请求地址
        secureuri: false, //是否需要安全协议，一般设置为false
        beforeSend: function (request) {
        },
        data: opt.data || {},
        fileElementId: opt.eleId || 'file1', //文件上传域的ID
        // dataType: 'html', //返回值类型 一般设置为json
        dataType: 'text', //返回值类型 一般设置为json
        success: function (data, status) {//服务器成功响应处理函数
            data = JSON.parse(data);
            if (data.code == 200) {
                data.opt = opt;
                cb && cb(data);
            } else {
                cb && cb(false);
                alert(data.error || '导入或上传失败');
            }
        },
        error: function (data, status, e) {//服务器响应失败处理函数
            console.log(e);
        }
    });
    return false;
}


var TableHeader = {};

/**
 * 监听input 事件
 * @param $ele
 * @param cb
 */
function onInput($ele, cb) {
    if ($ele.length) {
        cb = cb || function () {
            };
        $ele.unbind && $ele.unbind('input change propertychange').bind('input change propertychange', cb);
    }
}

function onChange($ele, cb) {
    if ($ele.length) {
        cb = cb || function () {
            };
        $ele.unbind && $ele.unbind('change').bind('change', cb);
    }
}

function onClick($ele, cb) {
    if (typeof $ele == 'string') {
        $ele = $($ele);
    }
    if ($ele.length) {
        cb = cb || function () {
            };
        $ele.unbind && $ele.unbind('click').on('click', cb);
    }
}

String.prototype.endWith = function (endStr) {
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d)
};

function destroyBtn() {

}

function createBtn(_this) {

}

/**
 * 按钮生成工具函数
 * @param contentHtml
 * @returns {*|jQuery|HTMLElement}
 */
function generatorBtn(contentHtml) {
    return $('<button class="btn btn-primary">' + contentHtml + '</button>')
}
/**
 * label: 按钮名称
 * class_:'按钮自定义class'
 * @param obj
 */
function genBtn(obj) {
    var $btn = generatorBtn(obj.label);
    if (obj.class_) $btn.addClass(obj.class_);
    return $btn;
}

/***
 * 按钮组生成工具函数
 * @returns {*|jQuery|HTMLElement}
 */
function generatorBtnGroup() {
    return $('<div class="btn-group" role="group" aria-label=""></div>')
}
function attachTips($btn, msg) {
    $btn.attr('data-type', 'info');
    $btn.attr('data-toggle', 'tooltip');
    $btn.attr('data-placement', 'top');
    $btn.attr('title', msg);
    return $btn;
}

/**
 * 权限按钮显示
 */
function renderBtn() {
    var $toolbar = $('.toolbar');
    if ($('.sub-body').length && $toolbar.length) {
        var path = window.location.pathname;
        // window.location.pathname
        $.when(window.parent.getLoginUser())
            .then(function (user) {
                var filter = _.filter(user.permissions, function (item) {
                    return !item.type
                });
                filter = _.groupBy(filter, function (item) {
                    return item.url.split(':')[0];
                });
                var $create = $('<button class="btn btn-primary btn-create"><i class="icon icon-plus" aria-hidden="true"></i> 新建</button>');
                var $update = $('<button type="button" class="btn btn-primary btn-update  disabled" disabled=""><i class="icon-pencil2" aria-hidden="true"></i> 修改</button>');
                var $delete = $('<button type="button" class="btn btn-primary btn-delete  disabled" disabled=""><i class="icon icon-cross" aria-hidden="true"></i> 删除</button>');
                var $upload = $('<a href="javascript:void(0)" class="btn btn-primary btn-upload  disabled" disabled="">上传缩略图</a>');
                var $distRole = $('<button class="btn btn-primary btn-dist-role  disabled" disabled="">指派角色</button>');
                var $updatePasswd = $('<button class="btn btn-primary btn-update-passwd  disabled" disabled="">修改密码</button>');
                var $dimission = $('<button  class="btn btn-danger btn-dimission  disabled" disabled="">离职</button>');
                var $return = $('<button  class="btn btn-primary btn-return  disabled" disabled="">恢复</button>');
                var $online = $('<button  class="btn btn-primary btn-online  disabled" disabled="">上|下线</button>');
                var $addNumebr = $('<button  class="btn btn-primary btn-number  disabled" disabled="">增加采购数量</button>');
                var $log = $('<button class="btn btn-primary btn-log  disabled" disabled="">查看日志</button>');
                var $createPurchaseOrder = $('<button class="btn btn-primary btn-create-order  disabled" disabled="">创建采购订单</button>');
                var $check = $('<button class="btn btn-primary btn-check  disabled" disabled="">审核</button>');
                var $paper = $('<button  class="btn btn-primary btn-paper  disabled" disabled="">打印合同</button>');
                var $pay = $('<button class="btn btn-primary btn-pay  disabled" disabled="">申请付款</button>');
                var $createBill = $('<button class="btn btn-primary btn-create-bill  disabled" disabled="">收货开单</button>');
                var $end = $('<button class="btn btn-primary btn-end  disabled" disabled="">终止执行</button>');
                var $foceEnd = $('<button class="btn btn-primary btn-force-end  disabled" disabled="">强制执行完毕</button>');
                var $applyPaper = $('<button class="btn btn-primary btn-apply-paper  disabled" disabled="">申请发票</button>');
                var $change = $('<button  class="btn btn-primary btn-change  disabled" disabled="">收货单变更</button>');
                var $chongdi = $('<button  class="btn btn-primary btn-chongdi  disabled" disabled="">冲抵</button>');
                var $hexiao = $('<button  class="btn btn-primary btn-hexiao  disabled" disabled="">核销</button>');
                var $payByAdvanceReceipt = $('<button  class="btn btn-primary btn-pay-by-ar  disabled" disabled="">预收款单付款</button>');
                var $btn = $('<button  class="btn btn-primary disabled" disabled=""></button>');
                var $allow = $('<button  class="btn btn-primary btn-allow disabled" disabled="">通过</button>');
                var $refuse = $('<button  class="btn btn-danger btn-refuse disabled" disabled="">拒绝</button>'),
                    $print = $('<button  class="btn btn-primary btn-print disabled" disabled="">打印</button>'),
                    $clear = $('<button  class="btn btn-primary btn-clear-zero disabled" disabled="">清零</button>');
                $updateBatch = $('<button  class="btn btn-primary btn-update-batch disabled" disabled="">更换批号</button>');
                /**
                 *  申请发票
                 * @type {any}
                 */
                var $applyInvoice = $('<button  class="btn btn-primary btn-apply-invoice  disabled" disabled="">申请发票</button>');
                if (path.indexOf('product/info/index') > -1) {
                    $toolbar.prepend($delete).prepend($update).prepend($create);
                } else if (path.indexOf('customer/supplier/index') > -1) {
                    $toolbar.prepend($check);
                } else if (path.indexOf('product/goods/index') > -1) {
                    $toolbar.prepend($hexiao.html('价格指数')).prepend($btn.addClass('upload-zhijian').html('质检单')).prepend($log).prepend($upload).prepend($delete).prepend($update).prepend($create);
                } else if (path.indexOf('product/msds/index') > -1) {
                    $create = attachTips($create, "上传MSDS");
                    $delete = attachTips($delete, "删除");
                    $update = attachTips($update, "更新");
                    $online = attachTips($online, "下线/正常");
                    $toolbar
                        .prepend($create.html('创建'))
                        .prepend($delete.html('删除'))
                        .prepend($update)
                        .prepend($online.html('下线'))
                    ;
                } else if (path.indexOf('product/offer/index') > -1) {
                    var $search = parseSearch();
                    $toolbar
                    // .prepend(genBtn({label: '批量上架', class_: 'batch-up '}))//
                    // .prepend(genBtn({label: '批量拼团', class_: 'batch-group '}))//
                    // .prepend($hexiao.html("下载模板").removeClass('disabled'))
                    // .prepend($chongdi.html("模板导入"))
                    // .prepend($log)
                        .prepend($delete)
                        .prepend($update)
                        .prepend($create);
                    if (!!$search.link) {
                        $toolbar.append($chongdi.html('关联'))
                    }
                } else if (path.indexOf('product/plant/index') > -1) {
                    $toolbar
                    // .prepend(genBtn({label: '批量上架', class_: 'batch-up '}))//
                        .prepend(genBtn({label: '上架下架', class_: 'batch-group '}))//
                        // .prepend($hexiao.html("成长天数管理").removeClass('disabled'))
                        .prepend($hexiao.html("成长图片管理").removeClass('disabled'))
                        .prepend($chongdi.html("上传植物卡片"))
                        // .prepend($log)
                        .prepend($delete)
                        .prepend($update)
                        .prepend($create)
                    ;
                } else if (path.indexOf('sales/userwx/index') > -1) {
                    $toolbar
                        .prepend($update.html('修改积分'));
                    ;
                } else if (path.indexOf('store/express/index') > -1) {
                    $allow = attachTips($allow, "通过");
                    $refuse = attachTips($refuse, "拒绝");
                    $log = attachTips($log, "查看日志");
                    $print = attachTips($print, "打印提货单");
                    $clear = attachTips($clear, "清零");
                    $delete = attachTips($delete, "删除");
                    $hexiao = attachTips($hexiao, "录入实提数");
                    $foceEnd = attachTips($foceEnd, "终止提货单");
                    $updateBatch = attachTips($updateBatch, "更换批号");
                    $toolbar.prepend($log)
                        .prepend($log)
                        .prepend($allow)
                        .prepend($refuse)
                        .prepend($clear)
                        .prepend($updateBatch)
                        .prepend($hexiao.html('录入实提数'))
                        .prepend($foceEnd.html('终止提货单'))
                        .prepend($delete)
                        .prepend($update.html('提单变更'))
                        .prepend($print)
                    ;
                } else if (path.indexOf('invoice/open/index') > -1) {
                    $toolbar.prepend($create.html('开票'))
                        .append($btn.html('查看已开票').addClass('view'))
                    //.append($delete.html('删除'))
                    ;
                } else if (path.indexOf('invoice/received/index') > -1) {
                    $delete = attachTips($delete, "删除");
                    $toolbar
                    //.append($btn.html('查看已收票').addClass('view'))
                    //.append($log)
                        .append($delete)
                        .append($create.html('记录流转'))
                        .append($btn.html('流转查看').addClass('view'));
                } else if (path.indexOf('invoice/custom/open-view') > -1) {
                    $toolbar.prepend($create.html('记录流转')).append($btn.html('流转查看').addClass('view'));
                } else if (path.indexOf('invoice/received/view') > -1) {
                    $toolbar.prepend($hexiao.html('收票确认')).prepend($create.html('记录流转')).append($btn.html('流转查看').addClass('view'));
                } else if (path.indexOf('invoice/custom/view') > -1) {
                    $toolbar.prepend($create.html('记录流转')).append($btn.html('流转查看').addClass('view'));
                } else if (path.indexOf('invoice/custom/opened') > -1) {
                    $toolbar.append($btn.html('查看发票').addClass('view'));
                } else if (path.indexOf('invoice/custom/open') > -1) {
                    $toolbar.prepend($create.html('开票')).append($btn.html('查看已开票').addClass('view'));
                } else if (path.indexOf('invoice/custom/index') > -1) {
                    $toolbar.prepend($create.html('收票')).append($btn.html('查看已收票').addClass('view'));
                } else if (path.indexOf('invoice/opened/index') > -1) {
                    $delete = attachTips($delete, "删除");
                    $toolbar.append($btn.html('查看流转')
                        .addClass('view'))
                        .append($delete)
                        .append($create.html('记录流转'));
                } else if (path.indexOf('invoice/custom/received') > -1) {
                    $toolbar.append($btn.html('查看发票').addClass('view'));
                } else if (path.indexOf('invoice/open/view') > -1) {
                    $delete = attachTips($delete, "删除");
                    $toolbar.prepend($create.html('记录流转')).append($btn.html('查看流转').addClass('view'))
                        .append($delete.html('删除'));
                } else if (path.indexOf('invoice/opened/view') > -1) {
                    $toolbar.prepend($create.html('记录流转')).append($btn.html('查看流转').addClass('view'));
                } else if (path.indexOf('product/order/index') > -1) {
                    // $toolbar.prepend($log);
                } else if (path.indexOf('sys/role/index') > -1) {
                    $toolbar.prepend($hexiao.addClass('btn-update-permission').html('修改权限')).prepend($btn.html('查看权限').addClass('view')).prepend($log).prepend($delete).prepend($update).prepend($create);
                } else if (path.indexOf('due-finance/purchase/index') > -1) {
                    $btn = attachTips($btn, "出纳核算前可删除");
                    $toolbar
                        .prepend($pay.html('付款'))
                        .prepend($check.html('领导审核').css({marginRight: '0'}))
                        .prepend($hexiao.html('出纳核算').css({marginRight: '0'}))
                        .append($log)
                        .append($paper.html('打印付款申请单'))
                        .append($btn.html('删除').addClass("btn-delete"))
                    ;
                } else if (path.indexOf('due-finance/payed/index') > -1) {
                    $btn = attachTips($btn, "删除");
                    $toolbar
                        .append($btn.html('删除已付款').addClass("btn-delete"))
                    ;
                } else if (path.indexOf('due-finance/sale/index') > -1) {
                    $toolbar
                        .prepend($pay.html('付款'))
                        .prepend($check.html('领导审核').css({marginRight: '0'}))
                        .prepend($hexiao.html('出纳核算').css({marginRight: '0'}))
                        .append($log)
                        .append($paper.html('打印付款申请单'));
                } else if (path.indexOf('due-finance/advance-pay/index') > -1) {
                    $btn = attachTips($btn, "删除，使用前有效");
                    $toolbar.prepend($log).prepend($update.html('查看预付款单使用'))
                        .prepend($create.html('创建预付款单'))
                        .append($btn.html('删除').addClass("btn-delete"))


                } else if (path.indexOf('sys/user/index') > -1) {
                    $toolbar.prepend($log).prepend($dimission).prepend($return).prepend($updatePasswd).prepend($distRole).prepend($delete).prepend($update).prepend($create);
                } else if (path.indexOf('sys/com/index') > -1) {
                    $toolbar
                    //.prepend($log).prepend($delete)
                        .prepend($update);
                    //.prepend($create).prepend($btn.html('公章管理').addClass('signature'));
                } else if (path.indexOf('sys/dep/index') > -1) {
                    $toolbar
                    //.prepend($log)
                        .prepend($delete).prepend($update).prepend($create);
                } else if (path.indexOf('purchase/purchase/index') > -1) {
                    $toolbar.prepend($createPurchaseOrder).prepend($log).prepend($addNumebr).prepend($online).prepend($delete).prepend($update).prepend($create);
                } else if (path.indexOf('purchase/order/index') > -1) {
                    $toolbar.prepend($foceEnd).prepend($end).prepend($createBill).prepend($log)
                        .prepend($pay).prepend($check).prepend($paper).prepend($update);
                } else if (path.indexOf('purchase/takeover/index') > -1) {
                    var $inStore = $('<button href="javascript:void(0)" class="btn btn-primary btn-in-store  disabled" disabled="disabled">入库</button>');
                    $toolbar
                        .prepend($inStore)
                        .prepend('<button href="javascript:void(0)" class="btn btn-primary btn-delete  disabled" disabled="disabled">删除</button>')
                        .prepend('<button href="javascript:void(0)" class="btn btn-primary btn-clear  disabled" disabled="disabled">清零</button>')
                        .prepend($log).prepend($change).prepend($paper.html('打印收货单')).prepend($check).append($applyInvoice);
                } else if (path.indexOf('gathering-finance/sale/index') > -1) {
                    $btn.attr('data-type', 'info');
                    $btn.attr('data-toggle', 'tooltip');
                    $btn.attr('data-placement', 'top');
                    $btn.attr('title', '订单已收款未创建发货单');
                    $toolbar.prepend($hexiao)
                        .prepend($chongdi.html('收款'))
                        .append($log)
                        .append($btn.html('撤销已收款').addClass("btn-chexiao"));
                } else if (path.indexOf('gathering-finance/purchase/index') > -1) {
                    $toolbar.prepend($chongdi.html('收款')).prepend($btn.html('申请退款').addClass('apply-back'))
                        .append($paper.html('打印退款申请函').addClass('transfer-bill'))
                        .append($hexiao.html('转化预付款单')).append($log)
                    //.append($paper.html('转化退款申请函').addClass('transfer-bill'))
                    ;
                } else if (path.indexOf('gathering-finance/account/index') > -1) {
                    $toolbar.prepend($log).prepend($update).prepend($create);
                } else if (path.indexOf('gathering-finance/advance-receipt/index') > -1) {
                    $delete = attachTips($delete, "删除，使用前有效");
                    $btn = attachTips($btn, "给订单付款");
                    $btn.addClass('pay-order');
                    $toolbar.prepend($log).prepend($update.html('查看预收款单使用'))
                        .prepend($create.html('新建预收款单'))
                        .append($delete.html('删除'))
                        .append($btn.html('给订单付款'));

                } else if (path.indexOf('gathering-finance/advance-receipt/account') > -1) {
                    $toolbar.append($pay.html('付款'))
                } else if (path.indexOf('gathering-finance/other/index') > -1) {
                    $toolbar.append($log).append($create).append($pay.html('收款'))
                        .append($delete).append($payByAdvanceReceipt.html('预收款单付款')).append($applyPaper.html('申请开票'));
                } else if (path.indexOf('due-finance/other/index') > -1) {
                    $toolbar
                        .prepend($pay.html('付款'))
                        // .append($pay.html('付款'))
                        .prepend($check.html('领导审核').css({marginRight: '0'}))
                        .prepend($hexiao.html('出纳核算').css({marginRight: '0'}))
                        .append($log).prepend($create)
                        .append($delete)
                        .append($btn.html('核销').addClass('hexioa'))
                        // .append($payByAdvanceReceipt.html('预付款单付款'))
                        .append($applyPaper.html('申请开票'));
                } else if (path.indexOf('invoice/receive/index') > -1) {
                    //$delete = attachTips($delete, "删除");
                    $toolbar
                        .append($create.html('收票'))
                        //.append($log)
                        .append($btn.html('查看已收发票').addClass('received'));
                    //.append($delete);
                } else if (path.indexOf('sys/setting/index') > -1) {
                    var btns = [genBtn({label: '增加一级菜单', class_: 'add'}), genBtn({label: '增加二级菜单', class_: 'sub'})];
                    window.btns = btns;
                    btns.map(function (item) {
                        $toolbar
                            .append(item);
                    });
                }
                $('[data-toggle="tooltip"]').tooltip();

            })
            .fail(function (e) {
                console.log(e)
            });
    }
}
function refreshPage() {
    window.location.href = window.location.href;
}
function setChecked(obj) {
    obj.prop('checked', 'checked').attr('checked', 'checked');
}
/**
 *  获取toolbar 上初始化的按你
 * @returns {[*]|*}
 */
function getToolBtns() {
    return window.btns;
}
function formatDuring(mss) {
    var items = [];
    var days = parseInt(mss / (1000 * 60 * 60 * 24));
    var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = (mss % (1000 * 60)) / 1000;
    if (days != 0) {
        items.push(days + ' 天 ')
    }
    if (hours != 0) {
        items.push(hours + ' 小时 ')
    }
    if (minutes != 0) {
        items.push(minutes + ' 分钟 ')
    }
    if (seconds != 0) {
        items.push(parseInt(seconds) + ' 秒 ')
    }
    if (items.length) {
        return items.join('')
    }
    return days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
}
/**
 *  form财务
 *  @param data 表单项数据
 */
function validateDialogForm(data, submit) {
    var form = {};
    data.map(function (item) {
        form[item.name] = {
            name: {
                row: '.col-xs-7',
                validators: $.extend({}, item.require ? {
                    notEmpty: {
                        message: item.label + '必填'
                    }
                } : {}, item.validator || {})
            },
        };
    });

    $('body #dialog-form' + data.formId)
        .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
        fields: form
    }))
        .off('success.form.fv').on('success.form.fv', function (e) {
        e.preventDefault();
        var form = parseSearch($(e.target).serialize());
        form = decodeObj(form, true);
        console.log(JSON.stringify(form));
        submit && submit(form);

    });

}
function genId() {
    return parseInt(Math.random() * 100000);
}
/**
 *  弹框增加表单
 */
function dialogForm(obj, isform) {
    var data = obj.data;
    var $formId = genId();
    var html = $(window.top.document).find('#dialog-form');
    var form = obj.form || {};
    form.id = genId();// 系统生成id
    data.formId = form.id;
    html = ejs.render(html.html(), {
        list: data,
        form: form,
        noForm: !!obj.noForm
    });
    if (!isform) {
        var layer1 = layerAlert({
            title: obj.title || '表单',
            body: html,
            full: true,
            //width: obj.width || '420px',
            shown: function (index) {
                obj.shown && obj.shown({index: index});
                $('.layui-layer-content').css('overflow', 'visible');
                validateDialogForm(data, obj.submit);
            },
            closeHide: function () {

            },
            okHide: function () {

            }
        });
        return layer1;
    } else {
        $('#' + obj.eleId).html(html);
        obj.shown && obj.shown();
        validateDialogForm(data, obj.submit);
    }

}
/**
 * 显示相册
 * @param json
 */
function layerPhoto(json) {
    //

    // {
    //     "title": "", //相册标题
    //     "id": 123, //相册id
    //     "start": 0, //初始显示的图片序号，默认0
    //     "data": [   //相册包含的图片，数组格式
    //     {
    //         "alt": "图片名",
    //         "pid": 666, //图片id
    //         "src": "", //原图地址
    //         "thumb": "" //缩略图地址
    //     }
    // ]
    // }


    layer.photos({
        photos: json
        , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });
}

function closeLayer(index) {
    return layer.close(index);
}
function layerAlert(opt) {
    var t = layer.open({
        type: opt.type || 1,
        title: opt.title,
        //  btn: ['按钮一'],
        shade: 0.3,
        anim: 0,
        area: opt.width || 'auto',
        resize: true,
        maxmin: opt.maxmin,
        success: function () {
        },
        yes: opt.okHide || function (item) {
        },
        cancel: opt.closeHide || function () {
        },
        //skin: 'layui-layer-rim', //加上边框
        // area: ['420px', '240px'], //宽高
        content: opt.body
    });
    if (opt.full) {
        //console.log('full->' + t)
        layer.full(t);
        $(window).resize(function () {
            layer.full(t);
        });
        $('.layui-layer-max').hide();
    }
    opt.shown && opt.shown(t);
    return t;
}
/**
 *
 * @param obj {w:{c:'cw'}}
 * @param str 'w.c'
 * @returns {*} 'cw'
 */
function readDotSplitProp(obj, str) {
    var obj_ = obj;
    str.split('.').forEach(function (item) {
        obj_ = obj_[item];
    })
    return obj_;
}

function writeDotSplitProp(obj, str, value) {
    var obj_ = obj;
    str.split('.').forEach(function (item) {
        obj_ = obj_[item];
    })
    return obj_;
}

/**
 * 菜单
 * @param list
 * @param canEdit 可编辑 true 可以
 */
function renderMenus(list, canEdit) {
    var menus_module = _.groupBy(list, function (item) {
        var url = item.url.substr(2);
        return url.substr(0, url.indexOf("/"));
    });
    var map_ = {
        sys: '菜单权限',
    };
    var item_check = "<p  style='font-size:22px;font-weight:500;' class='hp-perm-p'>菜单权限</p>", role_name = "";
    Object.keys(menus_module).map(function (key) {
        //     if (menus_module[key]) {
        //role_name = menus_module[key][0].roleName;
        item_check += '<p><label  style="padding-left: 0;font-size:14px;color:#777;font-weight:500;margin-right: 5px;"  class="checkbox-inline">' + ' \
                    </label>' +
            menus_module[key].map(function (it) {
                return '<label class="checkbox-inline"> \
                <input type="checkbox" id="' + it.id + '" ' + (canEdit ? ' ' : ' disabled checked ') + '> ' + it.permissionName + ' \
                    </label>';
            }).join('') + '</p>';
        // }
    });
    return item_check;
}

function getUnRead() {
    if ($('iframe').length) {
        return;
    }
    $.when(parent.getLoginUser())
        .then(function (res) {
            $('.navbar-default .navbar-right .dropdown > a').html(res.name + '<span class="caret"></span>')
        });
    // parent.getLogin
    // $.get('/notice/queryStatis/1/0', function (res) {
    //     if (res.code == 200) {
    //         $('.badge').html(res.data);
    //     }
    // });
    $.get('/pLetter/count?status=1&readStatus=0&size=5000', function (res) {
        if (res.code == 200) {
            $('.badge').html(res.data);
        }
    });
}
/***
 * 接口访问权限
 * @param list
 * @param canEdit 可编辑 true 可以
 */
function renderAccess(list, canEdit) {
    var menus_module = _.groupBy(list, function (item) {
        var url = item.url;
        return url.substr(0, url.indexOf(":"));
    });
    var map_ = {
        goods: '产品管理',
        offer: '报价管理',
        order: '订单管理',
        sale_cash_apply: '佣金管理',
        secretary: '秘书管理',
        lading_bill: '发货单管理',
        sale_send: '发货管理',
        'advance-receipt': '预付款管理',
        purchase: '采购单管理',
        purchaseOrder: '采购订单管理',
        purchaseOrderBill: '采购收货单管理',
        sale_gathering_finance: '销售应收明细',
        purchase_gathering_finance: '采购应收明细',
        other_gathering_finance: '其他应收明细',
        purchase_due_finance: '采购应付明细',
        sale_due_finance: '销售应付明细',
        other_due_finance: '其他应付明细',
        invoice_open: '待开发票',
        invoice_receive: '待收发票',
        apply_pay_bill: '采购付款申请单',
        invoice: '发票管理',
        reconciliation_provider: '供应商往来对账',
        reconciliation_clientele: '客户往来对账',
        send: '报表',
        reconciliation: '往来对账',

    };
    var item_check = "<p    style='font-size:22px;font-weight:500;' class='hp-perm-p'>数据权限</p>", role_name = "";
    Object.keys(map_).map(function (key) {
        if (menus_module[key]) {
            item_check += '<p><label  style="padding-left: 0;font-size:14px;color:#777;font-weight:500;margin-right: 5px;" class="checkbox-inline">' + map_[key] + ' \
                    </label>' +
                menus_module[key].map(function (it) {
                    return '<label class="checkbox-inline"> \
                <input type="checkbox"  id="' + it.id + '"  ' + (canEdit ? '  ' : ' disabled checked') + ' > ' + it.permissionName + ' \
                    </label>';
                }).join('') + '</p>';
        }
    });
    return item_check;
}


/***
 *
 * 税额
 * @param taxRatio 税率
 * @param total 价税合计金额
 * @returns {*}
 */
function taxTotal(taxRatio, total) {

    taxRatio = parseFloat(taxRatio);
    return parseFloat(toFixed(floatTool.multiply(floatTool.divide(total, (floatTool.add(1, taxRatio))), taxRatio), 2));
}
function formatTaxRatio(item) {
    if (item.taxRatio) {
        return (parseFloat(item.taxRatio) * 100) + '%'
    }
    return '-';
}
function getDefaultImgStr() {
    return '<a target="_blank" href="javascript:void(0);" title="点击预览"><img style="height:60px;border-radius:5px;" src="/admin/imgs/upload/default-img.png" /></a>'

}
/**
 *
 *  格式化列表数据
 */
function formatListsData(list, field) {
    var t = [], t1 = _.groupBy(list, field);
    Object.keys(t1).sort().reverse().map(function (item) {
        t.push(t1[item]);
    });
    return t;
}
function resetNumber(num) {
    var total1 = 0;
    $('.list-bill tr td:nth-child(' + num + ')').map(function (index, item) {
        if ($(item).find('[type=text]').length) {
            var numberThisTime = parseFloat($(item).find('[type=text]').val()) || 0;
            total1 = floatTool.add(total1, numberThisTime);
        } else {
            $(item).html(total1);
        }
    });
};

function compare() {

}
/**
 * 下拉选择框 opt.name ：dom元素名称, opt.change:所选值变更事件
 */
function selectGoods(opt) {
    var $g = $('[name=' + opt.name + ']');
    //
    if ($g.length) {
        if ($g.data('init'))return; // 防止重复初始化
        $.when(parent.window.getDataByUrl(opt.url || '/goods/query?size=50', opt.key || "goods"))
            .then(function (goods) {
                var $goodsId = $('<select name="' + opt.name + '"></select>');
                $('[name=' + opt.name + ']').replaceWith($goodsId);
                if (opt.placeholder) {
                    $goodsId.append('<option value="">' + (opt.placeholder ) + '</option>');
                }
                var list = (goods.list || goods);
                list.map(function (item) {
                    $goodsId.append('<option value="' + item.id + '">' + item.name + '</option>');
                });
                $goodsId.selectpicker({
                    liveSearch: true,
                });
                $goodsId.data('init', $goodsId);
                $goodsId.closest('.bootstrap-select').css('width', 'auto');
                $goodsId.on('changed.bs.select', function (e) {
                    var $t = $(e.target);
                    opt.change && opt.change($t.val(), $t)
                });
                if (opt.selected) {
                    $goodsId.selectpicker('val', opt.selected);
                }
            });
    }
}
/**
 * opt.ele
 * opt.name
 * @param opt
 */
function selectEle(opt) {
    var $g = opt.ele;
    //
    if ($g.length) {
        if ($g.data('init'))return; // 防止重复初始化
        $.when(parent.window.getDataByUrl(opt.url || '/goods/query?size=50', opt.key || "goods"))
            .then(function (res) {
                return selectpickerFn({
                    ele: $g,
                    selected: opt.selected || '',
                    name: opt.name,
                    list: res.list || res,
                    change: opt.change || function () {
                    }
                });
            });
    }
}
/**
 * opt.list 数据
 * opt.ele 元素
 * opt.placeholder 提示
 * opt.multiple  是否多选？
 * opt.name  名称
 * opt.change  事件
 * opt.selected  被选择值
 *
 * @param opt
 */
function selectpickerFn(opt) {
    if (opt.ele.data('init')) {
        opt.ele.selectpicker('destroy');
        /// opt.ele.selectpicker('render')
    }

    var $eleId = $('<select data-size="5" ' + (opt.multiple ? 'multiple' : '') + ' name="' + opt.name + '"></select>');
    opt.ele.replaceWith($eleId);
    if (opt.placeholder) {
        $eleId.append('<option value="">' + (opt.placeholder ) + '</option>');
    }
    opt.list.map(function (item) {
        $eleId.append('<option value="' + item.id + '">' + item.name + '</option>');
    });
    $eleId.selectpicker({
        liveSearchPlaceholder: opt.placeholder || '请输入关键字查找',
        size: 6,
        title: opt.label || '请选择,可多选',
        liveSearch: true,
    });
    $eleId.data('init', $eleId);
    $eleId.closest('.bootstrap-select').css('width', opt.width || 'auto');
    $eleId.on('changed.bs.select', function (e) {
        var $t = $(e.target);
        opt.change && opt.change($t.val(), $t)
    });
    if (opt.selected) {
        $eleId.selectpicker('val', opt.selected);
    }
}
/**
 *  解码对象字段
 * @param obj
 * @param isSerialize 是否 $.serialize 序列化对象
 */
function decodeObj(obj, isSerialize) {
    obj = obj || {};
    Object.keys(obj).map(function (item) {
        try {
            if (isSerialize) obj[item] = obj[item].replace(/\+/g, " ") // 替换+ 为空格， 此处用户解决西$.serialize 空格变+问题
            obj[item] = decodeURIComponent(((obj[item])));
        } catch (e) {
            console.log(e.message);
            obj[item] = obj[item];
        }
    });
    return obj;
}

/**
 *  系统初始化
 */
function sysInit() {

    var domain = getDomain();
    if (domain.indexOf('localhost') > -1) { //据此判断开发环境
        if ($('.setting-dev').length) { // sub page
            $('.setting-dev').show();
        }
    }
    /**
     *  系统初始化
     */
    if ($('.logo-lg').length) { // top page
        getLoginUser()
            .then(function (res) {
                var setting = res.setting;
                $('.logo-lg').html(setting.name)
            })
    }
}
/**
 *
 * ztree
 * @param obj eleId 元素ID
 * @returns {*}
 */
function zTree(obj) {
    var zTreeObj;
    obj.click = obj.click || function () {
        };
    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: obj.click
        }
    };
    // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
    var zNodes = [
        {
            name: "CRM管理", id: '1', open: true, children: [
            {name: "客户管理"}, {name: "销售人员管理"}, {name: "销售经理"}, {name: '销售秘书'}, {name: "供应商管理"}]
        },
        {name: "销售管理", open: true, children: [{name: "销售报价"}, {name: "销售订单"}, {name: "销售发货"}]},
        {name: "采购管理", open: true, children: [{name: "采购需求"}, {name: "采购订单"}, {name: "采购收货"}]},
        {name: "仓库管理", open: true, children: [{name: "仓库管理"}, {name: "库存报表"}]},
    ];
    zTreeObj = $.fn.zTree.init($('#' + obj.eleId), setting, obj.data || zNodes);
    return zTreeObj;
}


/**
 * get menus list
 * @returns {*}
 */
function getMenusList(opt) {
    if (opt) {
        return top.window.getDataByUrl(opt.url, opt.key + '_list' + Math.random());

    }
    return top.window.getDataByUrl('/category/list?size=' + maxSize, 'menus_list' + Math.random());
}

/**
 * get menus item list
 * @returns {*}
 */
function getMenusItemList() {
    return top.window.getDataByUrl('/categoryRelation/list?size=' + maxSize, 'menu_item_list' + Math.random());
}


/**
 * 下拉选择框 opt.name ：dom元素名称, opt.change:所选值变更事件
 */
function initSelect(opt) {
    var $g = $('[name=' + opt.name + ']');
    //
    if ($g.length) {
        if ($g.data('init'))return; // 防止重复初始化
        if (opt.data) { // 提供数据
            initS(opt.data);
        } else { // 服务点请求数据
            $.when(parent.window.getDataByUrl(opt.url, "S" + genId()))
                .then(function (list) {
                    initS(list.list || list);
                });
        }
    }
    function initS(list) {
        var $goodsId = $('<select name="' + opt.name + '"></select>');
        $('[name=' + opt.name + ']').replaceWith($goodsId);
        $goodsId.append('<option value="">全部' + (opt.label || '') + '</option>')
        list.map(function (item) {
            $goodsId.append('<option value="' + item.id + '">' + item.name + '</option>')
        });
        $goodsId.selectpicker({
            liveSearch: true,
        });
        $goodsId.data('init', $goodsId);
        $goodsId.closest('.bootstrap-select').css('width', 'auto');
        $goodsId.on('changed.bs.select', function (e) {
            var $t = $(e.target);
            opt.change && opt.change($t.val(), $t)
        });
        if (opt.selected) {
            $goodsId.selectpicker('val', opt.selected);
        }
    }
}
/**
 *  动态生成面包屑导航
 */
function dynamicGenBreadNav() {
    var onLevel = $('.module-nav').find('.active a').text();
    var leaf = $(top.window.document).find('.treeview.active > .treeview-menu').find('li.active a').text();
    var leafNav = $(top.window.document).find('.treeview.active > a').text();
    console.log('首页>' + onLevel + '>' + leafNav + '>' + leaf);
}

function upload(lab, ratio) {
    ratio = ratio || {};
    if (ratio.uploadBtn) { // 是否上传按钮
        return $(ratio.class_ || '.select-file').$upload({
            w: ratio.w || 185,
            h: ratio.h || 164,
            url: ratio.url,
            noJcrop: ratio.noJcrop,
            extraData: ratio.extraData,
            label: ratio.label || '',
            submitEachTime: ratio.submitEachTime || '',
            submit: function (path) {
                if (ratio.submit) {
                    ratio.submit(path)
                } else {
                    $(ratio.preview || '.preview').attr('src', path);
                }
            }
        })
    }
    dialogForm({
        title: '上传' + lab,
        fullScreen: true,
        data: [
            {
                type: 'upload-dialog',
                label: lab,
                require: true, // 是否必填
                name: 'upload',
                value: '',
                num: 8,
                labelNum: 2,
                validate: 'ipt  validate[required]',
                btnClass: 'select-file',
                btn: {
                    class_: '9 col-xs-offset-1'
                }
            },
        ],
        width: ratio.width || '',
        shown: function (obj) {
            $('.select-file').$upload({
                w: ratio.w || 185,
                h: ratio.h || 164,
                noJcrop: ratio.noJcrop,
                submit: function (path) {
                    if (ratio.submit) {
                        ratio.submit(path)
                    } else {
                        $(ratio.preview || '.preview').attr('src', path);
                    }
                }
            })
        },
        noForm: true,
        submit: function (data) {
        }
    }, true);
}

function loadResource(obj) {
    obj.type = obj.type || 'js';
    if (obj.type.toUpperCase() == 'JS') {
        var script = document.createElement("script");
        script.src = obj.url;
        document.head.appendChild(script);
    }
    if (obj.type.toUpperCase() == 'FONT') {
        var script = document.createElement("script");
        script.src = obj.url;
        document.head.appendChild(script);
    }
}

/**
 *  通过URL判断是否是否图片
 * @param url
 */
function isImg(url) {

}
function uploadFn(lab, ratio, cb) {
    ratio = ratio || {};
    dialogForm({
        title: '上传' + lab,
        fullScreen: true,
        data: [
            {
                type: 'upload-dialog',
                label: lab,
                require: true, // 是否必填
                name: 'upload',
                labelStyle: ratio.style || '',
                value: '',
                num: ratio.num || 8,
                labelNum: ratio.labelNum || 2,
                validate: 'ipt  validate[required]',
                btnClass: 'select-file form-submit',
                btn: {
                    class_: '9  '
                }
            },
        ],
        shown: function (obj) {
            ratio.shown && ratio.shown();
            $('.select-file').$upload({
                w: ratio.w,
                h: ratio.h,
                url: ratio.url || '',
                plain: ratio.plain || false,//非图片文件
                previewClass: ratio.preview || 'preview',
                noCrop: !!(ratio.noCrop + '') ? ratio.noCrop : true,//没有裁剪
                submit: function (path) {
                    cb && cb({
                        fileId: $('#target').data('fileId'),
                        layerIndex: (obj.index),
                        path: path.path,
                        data: path
                    })
                }
            })
        },
        noForm: true,
        submit: function (data) {
            console.log(data);
        }
    });
}
/**
 * 裁剪
 * ration.w
 * ration.h
 * ration.path
 * ration.fileId
 * @param lab string
 * @param ratio object
 * @param cb
 */
function jcropFn(lab, ratio, cb) {
    ratio = ratio || {};
    var $index = dialogForm({
        title: '' + lab,
        fullScreen: false,
        data: [
            {
                type: 'jcrop-dialog',
                label: lab,
                require: true, // 是否必填
                name: 'upload',
                labelStyle: ratio.style || '',
                value: '',
                num: ratio.num || 8,
                labelNum: ratio.labelNum || 2,
                validate: 'ipt  validate[required]',
                btnClass: 'select-file form-submit',
                btn: {
                    class_: '9  '
                }
            },
        ],
        shown: function (obj) {
            ratio.shown && ratio.shown();
            $.$jCrop({
                w: ratio.w,
                h: ratio.h,
                path: ratio.path,
                fileId: ratio.fileId,
                submit: function (path) {
                    layer.closeAll();//关闭弹框
                    ratio.submit && ratio.submit(path)
                }
            })
        },
        noForm: true,
        submit: function (data) {
            console.log(data);
        }
    });
}

var maxSize = 100000;


/**
 * 执行组合排列的函数
 * example:［'白色','黑色','金色','粉红色'］；内存大小有［'16G','32G','64G','128G'］，版本有［'移动','联通','电信'］，要求写一个算法，实现［［'白色','16G','移动'］, ['白色','16G','联通'] ...］这样的组合
 * @param array
 * @returns {*}
 */
function doExchange(arr) {
    var len = arr.length;
    // 当数组大于等于2个的时候
    if (len >= 2) {
        // 第一个数组的长度
        var len1 = arr[0].length;
        // 第二个数组的长度
        var len2 = arr[1].length;
        // 2个数组产生的组合数
        var lenBoth = len1 * len2;
        //  申明一个新数组,做数据暂存
        var items = new Array(lenBoth);
        // 申明新数组的索引
        var index = 0;
        // 2层嵌套循环,将组合放到新数组中
        for (var i = 0; i < len1; i++) {
            for (var j = 0; j < len2; j++) {
                items[index] = arr[0][i] + "," + arr[1][j];
                index++;
            }
        }
        // 将新组合的数组并到原数组中
        var newArr = new Array(len - 1);
        for (var i = 2; i < arr.length; i++) {
            newArr[i - 1] = arr[i];
        }
        newArr[0] = items;
        // 执行回调
        return doExchange(newArr);
    } else {
        return arr[0];
    }
}

//执行
// var array = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']];
// var arr1 = [['a','b','c']];

// console.log(doExchange(array));


var jsonToFetchParam = function (obj, prefix) {
    var tmp = [];
    var t = prefix ? (prefix + '.') : '';
    Object.keys(obj).map(function (item) {
        //tmp.key
        if (obj[item] instanceof Array) { // 数据形式
            obj[item].map(function (ite, index) {
                var ti = '';
                if (typeof ite == 'number' || typeof ite == 'string' || typeof ite == 'boolean') {
                    ti = t + item + '[' + index + ']' + '=' + ite;
                } else {
                    ti = jsonToFetchParam(ite, t + item + '[' + index + ']');
                }
                tmp.push(ti);
            })
        } else if (typeof obj[item] == 'object') {
            var ti = jsonToFetchParam(obj[item], t + item);
            tmp.push(ti);
        } else if (typeof obj[item] != 'function') {
            tmp.push(t + item + '=' + obj[item]);
        }
    });
    return tmp;
}
/**
 * 复杂对象传参工具函数
 * @param obj
 */
var getQueryStr = function (obj) {
    obj = jsonToFetchParam(obj);
    return _.flatten(obj);
}